import * as crypto from 'crypto'
import { WPSParams } from './WPSRequest'
import * as qs from 'querystring'

export class WPSContext {
  host: string
  appId: string
  appKey: string

  constructor(host: string, appId: string, appKey: string) {
    this.host = host
    this.appId = appId
    this.appKey = appKey
  }

  abs(url: string) {
    // if (url.indexOf('http') >= 0) {
    //   return url
    // }
    return `${this.host}${url}`
  }

  sha1(content: string) {
    const sha1 = crypto.createHash('sha1')
    return sha1.update(content).digest('hex')
  }

  sha256(content: string) {
    const sha256 = crypto.createHash('sha256')
    return sha256.update(content).digest('hex')
  }

  hmacSha256(content: string) {
    const sha256 = crypto.createHmac('sha256', this.appKey)
    return sha256.update(content).digest('hex')
  }

  md5(content: string) {
    const md5 = crypto.createHash('md5')
    return md5.update(content).digest('hex')
  }

  query(params:WPSParams){
    params = this.removeUndefinedOrNullParams(params)
    return qs.stringify(params)
  }

  stringify(params:WPSParams){
    params = this.removeUndefinedOrNullParams(params)
    return JSON.stringify(params)
  }

  private removeUndefinedOrNullParams(params:WPSParams){
    let values:WPSParams = {}
    for(let k of Object.keys(params)){
      let v = params[k]
      if(typeof v == 'undefined' || v == null)
        continue
      values[k] = v
    }
    return values
  }

  sign2(
    method: string,
    url: string,
    body: string = '',
    contentType: string = 'application/json'
  ) {
    const ver = "WPS-2"
    const date = new Date().toUTCString()
    const md5 = this.md5(body)
    const sha1 = this.sha1(this.appKey + md5 + contentType + date)
    const auth = `${ver}:${this.appId}:${sha1}`

    return {
      'Content-Type': contentType,
      'Content-Md5': md5,
      'Date': date,
      'Authorization': auth
    }
  }

  sign(
      method: string,
      url: string,
      body: string = '',
      contentType: string = 'application/json'
  ) {
    const ver = "WPS-4"
    const date = new Date().toUTCString()
    let sha256 = ''
    if (body != '') {
      sha256 = this.sha256(body)
    }
    const signStr = `${ver}${method}${url}${contentType}${date}${sha256}`
    const sign = this.hmacSha256(signStr)
    const auth = `${ver} ${this.appId}:${sign}`

    return {
      'Content-Type': contentType,
      'Wps-Docs-Date': date,
      'Wps-Docs-Authorization': auth
    }
  }
}
